<template>
  <div>
    <el-form label-width="100px" style="width:100%;">
      <!-- 规格表单 -->
      <div v-if="hasModel">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品规格">
              <div class="add-form" @click="showModelDialog"><i class="el-icon-plus"></i>添加规格</div>
            </el-form-item>
            <el-dialog title="商品规格项目" :visible.sync="visibleModelDialog" width="30%">
              <el-row>
                <el-col>
                  <h4>常用规格</h4>
                  <div @click="checkGoodsModel" style="text-align:center;">
                    <el-checkbox-group
                      v-model="checkedModels" :max="2">
                      <el-checkbox class="goods-model-item"
                                   v-for="(model, index) in commonModels"
                                   :label="model" :key="index" border size="mini"
                      >{{model}}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                  <div style="margin-top:10px;">
                    <span style="color:#409EFF;margin:0 10px;">已选：</span>{{checkedModels.join('，')}}
                  </div>
                </el-col>
              </el-row>
              <div class="button-group__right">
                <el-button type="default" @click="visibleModelDialog = false">取消</el-button>
                <el-button type="primary" @click="confirmGoodsModel">确定</el-button>
              </div>
            </el-dialog>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <div v-if="checkedModels.length > 0" v-for="(modelItem, index) in specs" :key="index">
              <div class="model-item">
                <div class="model-name">
                  {{modelItem.type}}
                  <i class="el-icon-close" @click="delModelItem(index)"></i>
                </div>
                <div class="sub-model-wrap">
                  <input-box v-for="(item, index) in modelItem.children" :key="index"
                             @edit="editSubModel"
                             @cancel="cancelSubModelItem(modelItem)"
                             @delete="delSubModel"
                             :index="index" :target="modelItem" :content="item"
                             @blur="editSubModel">
                  </input-box>
                  <div class="add-form"
                       v-show="!modelItem.isInputSubModel"
                       @click="addSubModel(modelItem)"
                  >
                    <i class="el-icon-plus"></i>添加标签
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-table :data="tableData" border style="width: 95%;margin-left:20px; border-radius:4px;">

        <el-table-column prop="spec0" :label="specs[0].type" v-if="specs.length > 0" align="center" width="150">
        </el-table-column>

        <el-table-column prop="spec1" :label="specs[1].type" v-if="specs.length == 2" align="center" width="150">
        </el-table-column>

        <el-table-column label="图片" align="center" width="100">
          <template slot-scope="scope">
            <img v-if="scope.row.modelUrl"
                 @click="sel_img(scope.$index, scope.row)"
                 :src="scope.row.modelUrl"
                 style="width:100%;height:100%;">
            <div class="select_img" v-else @click="sel_img(scope.$index, scope.row)"><i class="el-icon-plus"></i></div>
            <el-dialog title="选择图片" :visible.sync="sleImg" style="text-align: left;">
              <sel-img-photogallery ref="selImg" type="03" @select="onSelectImgs"></sel-img-photogallery>
            </el-dialog>
          </template>
        </el-table-column>
        <el-table-column class="model-price" ref="modePriceColumn" label="价格" align="center" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.modelPrice"
                             maxlength="10"
                             :precision="2"
                             :step="0.1"
                             style="width: 100px"
                             :controls='false'
                             placeholder="价格">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column class="virtual-price" ref="virtualPriceColumn" label="虚拟价" align="center" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.virtualPrice"
                             maxlength="10"
                             :precision="2"
                             :step="0.1"
                             style="width: 100px"
                             :controls='false'
                             placeholder="虚拟价">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column class="cost-price" ref="costPriceColumn" label="参考成本价" align="left" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.costPrice"
                             maxlength="10"
                             :precision="2"
                             :step="0.1"
                             style="width: 100px"
                             :controls='false'
                             placeholder="参考成本价">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="库存" align="center" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.modelStorage"
                             maxlength="10"
                             :precision="2"
                             :step="0.1"
                             style="width: 100px"
                             :controls='false'
                             placeholder="库存">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" width="80">
          <template slot-scope="scope">
            <el-input v-model="scope.row.modelUnit"
                      maxlength="10"
                      placeholder="单位">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="重量" align="center" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.weight"
                      maxlength="10"
                      :precision="2"
                      :step="0.1"
                      style="width: 100px"
                      :controls='false'
                      placeholder="重量">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="体积" align="center" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.volume"
                      maxlength="10"
                      :precision="2"
                      :step="0.1"
                      style="width: 100px"
                      :controls='false'
                      placeholder="体积">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="库存预警值" align="center" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.stocksForewarn"
                      maxlength="10"
                      :precision="2"
                      :step="0.1"
                      style="width: 100px"
                      :controls='false'
                      placeholder="库存预警值">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="扫码购编码" align="center" width="250">
          <template slot-scope="scope">
            <el-input v-model="scope.row.modelCode"
                      maxlength="40"
                      placeholder="编码">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格编号" align="center" width="120">
          <template slot-scope="scope">
            <p>{{scope.row.goodsModelSn}}</p>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
  import dictionary from './../../../util/pds/dictionary'
  import selImgPhotogallery from '@/components/pds/common/sel_img_photogallery'

  export default {
    components: {selImgPhotogallery},
    props: {
      hasModel: {
        type: Boolean,
        required: true
      },
      goodsInfo: {
        type: Object
      },
      type: {
        type: Boolean,
        default() {
          return true
        }
      }
    },
    data() {
      return {
        commonModels: dictionary.commonModels,
        modelItem: {},
        modelList: [],
        // 选择的规格名称
        checkedModels: [],
        // 添加的标签栏
        selectModels: {},
        specs: [],
        newSpecName: ['', ''],
        visibleModelDialog: false,
        // 规格信息列表
        goodsModels: [],
        isInputSubModel: false,
        subModelLength: 29,
        // goodsInfo:'',
        sleImg: false,
        imgIndex: 0,
        flag: true
      }
    },
    computed: {
      // 表格数据
      tableData() {
        var arr = this.modelList;
        for (var i = 0; i < arr.length; i++) {
          arr[i].spec0 = arr[i].modelName[0]
          arr[i].spec1 = arr[i].modelName[1]
        }
        return arr
      }
    },
    watch: {
      'goodsInfo': {
        handler: function (val,oldVal) {
          this.modelItem = {
            modelPrice: val.marketPrice,
            modelUrl: val.thumbUrl,
            modelUnit: val.unit,
            modelStorage: val.storage,
            virtualPrice: val.virtualPrice,
            modelCode: '',
            costPrice: '',
            weight: '',
            volume: '',
            stocksForewarn: '',
          }
          // val && this.initData()
          console.log(this.flag);
          if(this.flag && this.type) {
            this.initData(val)

          }
        },
        deep: true
      }
    },
    methods: {
      //选择图片
      sel_img(index, row) {
        this.sleImg = true;
        this.imgIndex = index;
      },
      onSelectImgs(imgs) {
        this.tableData[this.imgIndex].modelUrl = imgs[0].picUrl;
        this.sleImg = false;
      },
      initData(val) {
        console.log(val)
        if(val.attrMap) {
          console.log(val);
          for(let key in val.attrMap) {
            this.checkedModels.push(key)
            var obj = {}
            obj.type = key;
            obj.children = val.attrMap[key]
            this.specs.push(obj)
          }
          this.flag = false
        }
        if(val.modelList) {
          val.modelList.forEach(item => {
            let modelName = item.modelName.split(',')
            item.modelName = modelName
          })
          this.modelList = val.modelList
          this.flag = false
        }
      },
      /**
       * 规格相关
       */
      showModelDialog() {
        this.visibleModelDialog = true
      },
      // 展示规格数据, 将string to array, 返回array[index]
      transModel(model, index) {
        let modelArr = model.split(',')
        return modelArr[index]
      },
      checkGoodsModel(e) {

        let length = this.checkedModels.length
        let checked = this.checkedModels.indexOf(e.target.defaultValue) > 0
        if (e.target.localName == 'input' && length == 3 && !checked) {
          this.$message({
            showClose: true,
            message: '规格最多选择3项。',
            type: 'warning'
          })
        }
      },
      /**
       * 监听 checkedModels 时调用, 生成selectModels =>
       *  {
       *      '1': { id: 1, name: '尺码', subModelId: [], subModelName: []}
       *  }
       *  isInputSubModel 用于标示是否隐藏‘添加标签’按钮
       */
      genModels(val, oldVal) {
        let that = this
        if (!Array.isArray(val)) {
          console.log('genModels参数错误');
          return;
        }
        let models = {}
        val.map((item, index) => {
          let id = that.commonModels.indexOf(item) + 1
          // if (!oldVal.indexOf(item) && (that.selectModels[id] == null)) {
          models[id] = {
            id: id,
            name: item,
            subModelName: [],
            subModelId: [],
            isInputSubModel: false
          }
        })
        that.selectModels = models
      },
      /**
       * 确认选择规格类型(颜色,尺寸等), 选择的类型会放入checkedModels(array)
       * 通过 Vue的 watcher 监听 checkedModels 有变化时调用 genModels 生成商品的规格选项
       */
      confirmGoodsModel(e) {
        if (this.checkedModels.length < 1) {
          this.$message({
            showClose: true,
            message: '请选择规格',
            type: 'warning'
          })
          return;
        }
        // 说明: 根据选中的规格动态生成model对象
        let arr = []
        this.checkedModels.forEach((item,index) => {
          let obj = {}
          obj.type = item;
          obj.children = []
          this.specs.push(obj)
          if(this.specs.length == 3) {
            this.specs.splice(1,1)
          }
        })
        // this.specs = arr
        console.log(this.specs);
        // 关闭对话框
        this.visibleModelDialog = false
      },
      // 删除规格类型, 如: 颜色, 尺寸等
      delModelItem(index) {
        this.checkedModels.splice(index, 1)
        this.specs.splice(index, 1)
        // 刷新 mySpecPrices
        var myDefaultAddPrices = JSON.parse(JSON.stringify(this.modelList));
        this.mySpecPrices(this.specCombinations(), myDefaultAddPrices)
      },
      /**
       *  添加规格标签, 规格标签id从30开始递增(不连续)
       *  subModelLength记录标签历史最多数量
       *  isInputSubModel 在新增标签后为true, 隐藏添加按钮
       */
      addSubModel(modelItem) {
        console.log(modelItem.children);
        let modelName = ''
        modelItem.children.push(modelName)
        console.log(modelItem);
      },
      // 规格组合数组
      specCombinations() {
        console.log(this.specs)
        var arrWra = [];
        // 有2个规格type
        if (this.specs.length == 2) {
          var arr1 = this.specs[0].children
          var arr2 = this.specs[1].children
          // 判断arr1是否为[], 如果是 为其添加个空字符串占位
          if (arr1.length == 0) {
            arr1 = ['']
          }
          if (arr2.length == 0) {
            arr2 = ['']
          }
          var arr = []
          for (var t = 0; t < arr1.length; t++) {
            for (var i = 0; i < arr2.length; i++) {
              arr = []
              arr.push(arr1[t])
              arr.push(arr2[i])
              arrWra.push(arr)
            }
          }
          console.log(arrWra)
          return arrWra
          // 只有1个规格type
        } else if (this.specs.length == 1) {
          var arr = this.specs[0].children
          if (arr.length == 0) {
            arr = ['']
          }
          for (var i = 0; i < arr.length; i++) {
            var _arr = []
            _arr.push(arr[i])
            arrWra.push(_arr)
          }
          console.log(arrWra)
          console.log('arrWra............')
          return arrWra
        }
      },
      // 绑定inputBox@delete 非编辑状态点击x, 删除规格标签
      delSubModel(data) {
        const index = data.index;
        const spec = data.target.children
        console.log(spec);
        spec.splice(index, 1)
        console.log(spec);
        console.log(this.specs);
        // // 刷新 mySpecPrices
        var myDefaultAddPrices = JSON.parse(JSON.stringify(this.modelList));
        this.mySpecPrices(this.specCombinations(), myDefaultAddPrices)
      },
      // 绑定inputBox@edit 点击‘铅笔’时进入编辑状态
      editSubModel(data) {
        console.log(data);
        data.target.children[data.index] = data.content
        console.log(this.specs);
        var myDefaultAddPrices = JSON.parse(JSON.stringify(this.modelList));
        var specCombinations = this.specCombinations()
        console.log(specCombinations);
        console.log(myDefaultAddPrices);
        this.mySpecPrices(specCombinations, myDefaultAddPrices)
      },
      // 数据更新
      mySpecPrices(specCombinations, myDefaultAddPrices) {
        var arrWra = []
        // 规格组合 数组
        var arr = specCombinations || []
        // if(arr.length == this.modelList.length) {
        //   this.modelList.forEach((item,index) => {
        //     item.modelName = arr[index]
        //     console.log(arr[index]);
        //   })
        //
        // }else {
          for (var i = 0; i < arr.length; i++) {
            // 新增 规格价格 项
            var obj = JSON.parse(JSON.stringify(this.modelItem));
            obj.modelName = arr[i];
            // !注意 a类型为数组
            // 对比 新的 规格组合数组 与原价格数组
            var oldItem = this.modelList.filter((element) => {
              return element.modelName + "" === arr[i] + "";
            })
            var newItem = this.modelList.filter((element) => {
              return element.modelName + "" != arr[i] + "";
            })
            // // 注意这里用的是length因为 空数组,空对象的布尔值为true
            // // 旧规各项价格
            if (oldItem.length) {
              obj = oldItem[0]
            }
            arrWra.push(obj)
          }
          this.modelList = arrWra
        // }
      },
      // 绑定inputBox@cancel 在inputBox没有值, 点击x时调用, 删除规格标签
      cancelSubModelItem(modelItem) {

      },
      /**
       *  生成规格组合(笛卡尔积)
       *  参数为多个数组, combine([1, 3], ['a', 'b']) => [[1, "a"], [1, "b"],[3, "a"],[3, "b"]]
       *  特殊用法: 使用apply调用, 如: this.combine.apply(this.combine, [[1, 3], ['a', 'b']])
       *  特殊用法: 使用call调用, 如: this.combine.apply(this.combine, [1, 3], ['a', 'b'])
       *  方便在有未知个参数时使用.
       */
      combine() {
        return Array.prototype.reduce.call(arguments, function (a, b) {
          var ret = [];
          a.forEach(function (a) {
            b.forEach(function (b) {
              ret.push(a.concat([b]));
            });
          });
          return ret;
        }, [[]]);
      },

    }

  }
</script>

<style scoped>
  .select_img {
    width: 50px;
    height: 50px;
    line-height: 50px;
    border: 1px dashed #c0ccda;
    background-color: #fbfdff;
    font-size: 18px;
    color: #8c939d;
    cursor: pointer;
    border-radius: 6px;
    margin: 0 auto;
  }

  .goods-info-wrap {
    padding: 0 20px;
  }

  /* 标题 */
  .item-title {
    margin-top: 15px;
    margin-bottom: 24px;
    padding-bottom: 10px;
    font-size: 14px;
    line-height: 16px;
    border-bottom: 1px solid #e9e9e9;
  }

  .item-title span {
    display: block;
    padding-left: 10px;
    margin-right: 5px;
    border-left: 3px solid #5491de;
  }

  .item-title-tips {
    display: inline-block;
    margin-left: 10px;
    color: #999999;
    font-size: 12px;
  }

  .picturePreviewDialog {
    margin: auto;
    width: 50%;
    border: 1px solid #dcdfe6;
    border-radius: 8px;
  }

  .goods-form-input {
    width: 286px;
    margin-right: 10px;
  }

  .goods-category {
    border: 1px solid #e9e9e9;
    margin-top: 10px;
    width: 286px;
    border-radius: 3px;
    max-height: 200px;
    overflow: scroll;
  }

  .add-form {
    width: 80px;
    padding-left: 5px;
    border: 1px dashed #e9e9e9;
    border-radius: 3px;
    font-size: 14px;
  }

  .add-model {
    display: inline-block;
    padding: 3px 10px 3px 10px;
    border: 1px dashed #e9e9e9;
    border-radius: 3px;
    color: #606266;
    font-size: 12px;
    margin-top: 10px;
    margin-bottom: 20px;
  }

  .button-group__center {
    margin-top: 20px;
    text-align: center;
  }

  .button-group__right {
    margin-top: 20px;
    margin-right: 10px;
    text-align: right;
  }

  /* 规格相关 */
  .goods-model-item {
    margin: 10px;
  }

  .model-item {
    display: flex;
    align-items: center;
    margin: 20px;
  }

  .model-name {
    box-sizing: border-box;
    height: 32px;
    font-size: 14px;
    padding: 5px 15px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
  }

  .model-name i {
    margin-left: 10px;
  }

  .sub-model-wrap {
    position: relative;
    display: inline-block;
    width: 50%;
    margin-left: 30px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
    padding: 10px;
  }

  .sub-model-wrap::before {
    content: '';
    display: block;
    position: absolute;
    top: 50%;
    margin-top: -12px;
    left: -12px;
    border-bottom: 12px solid transparent;
    border-top: 12px solid transparent;
    border-right: 12px solid #dcdfe6;
  }

  .sub-model-wrap::after {
    content: '';
    display: block;
    position: absolute;
    left: -10px;
    top: 50%;
    margin-top: -12px;
    border-bottom: 12px solid transparent;
    border-top: 12px solid transparent;
    border-right: 12px solid #fff;
  }

  .sub-model-wrap .add-form {
    display: inline-block;
    padding-top: 5px;
    padding-bottom: 5px;
  }

  .sub-model-item {
    display: inline-block;
  }

  .sub-model-item i {
    font-weight: bold;
  }

  .sub-model-item__confirm {
    display: inline-block;
    height: 32px;
    line-height: 30px;
    padding: 0px 10px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
    font-size: 14px;
    box-sizing: border-box;
  }

  /* 服务相关 */
  .service-form .el-button {
    border: none;
  }

  .service-form {
    margin-top: 20px;
  }

  /* 通用样式 */
  .input-icon {
    color: #409EFF;
    font-weight: bold;
  }

  .input-icon:hover {
    color: #66b1ff;
  }
</style>

<style>
  /* 覆盖框架原生样式  不可加scope */
  .add-goods .el-dialog__header {
    border-bottom: 1px solid #dcdfe6 !important;
  }

  .add-goods .el-table--enable-row-hover .el-table__body tr:hover > td {
    background: #fff;
  }

  .add-goods .el-table__row:hover {
    background: unset;
  }

  .item-title .el-tooltip {
    color: #666;
  }

  .add-goods .el-input__suffix-inner {
    line-height: 32px;
  }

  .add-goods .el-input--suffix .el-input__inner {
    padding-right: 40px;
  }

  .model-pic-uploader .el-upload--text {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px;
  }
</style>
